package deom1;

public class MyLinkedList {

    public static class LinkedNode {
        int value;
        LinkedNode next;

        LinkedNode(int value) {
            this.value = value;
        }
    }

    LinkedNode head;

    /*
     * 打印
     * */
    public void printList() {
        LinkedNode ret = head;
        while (ret != null) {
            System.out.print(ret.value+" ");
            ret = ret.next;
        }
        System.out.println();
    }

    /*
     * 求大小
     * */
    public int linkSize() {
        int count = 0;
        LinkedNode ret = head;
        while (ret != null) {
            count++;
            ret = ret.next;
        }
        return count;
    }


    /*
     * 头插
     * */
    public void addInsert(int val) {
        LinkedNode node = new LinkedNode(val);
        if (head == null) {
            head = node;
        } else {
            node.next = head;
            head = node;
        }
    }

    /*
     * 尾插
     * */
    public void fastInsert(int val) {
        LinkedNode node = new LinkedNode(val);
        if (head == null) {
            head = node;
        } else {
            LinkedNode ret = head;
            while (ret.next != null) {
                ret = ret.next;
            }
            ret.next = node;
        }
    }

    /*
     * 在第 pos 位后面插入 val
     * */
    public void posInsert(int pos,int val) {
        LinkedNode node = new LinkedNode(val);
        if (pos <= 0 || pos > linkSize()) {
            System.out.println("Pos is No !");
            return;
        }
        if (pos == linkSize()) {
            fastInsert(val);
            return;
        }
        int count = pos - 1;
        LinkedNode ret = head;
        while (count != 0) {
            ret = ret.next;
            count--;
        }
        node.next = ret.next;
        ret.next = node;

    }
}
